<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v9;

use think\Controller;
use app\api\model\Authority;

use app\api\model\OrderModel;
use app\api\model\Reimbursement;
use constant\config;
use think\Cache;


use think\Request;
use think\Exception;
use app\api\validate;
use  app\api\model\Approval;
use Think\Db;


class MaterialScience extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    protected $pdf;


    public function _initialize()
    {
        $this->model = new Authority();

        $this->us = Authority::check(1);

    }


    /**
     * 获取库存列表
     */
    public function Stock_list()
    {
        $data = Request::instance()->post(['type', 'ok']);
        if ($data['type'] == 0) {
            $custom = db('custom_material')->field('id,company,stock_name,latest_cost,number,created_time,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where('number', 'neq', 0)->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 0;
            }
        } else if ($data['type'] == 99) {
            $cust = db('purchase_usage')->field('id,company,stock_name,latest_cost,number,created_time,content,remake')->where('type', 1)->where('number', 'neq', 0);
            if (isset($data['ok']) && $data['ok'] != '') {
                $cust->where(['status' => 3]);
            }
            $custom = $cust->where('store_id', $this->us['store_id'])->order('created_time desc')->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 99;
            }
        } else if ($data['type'] == 98) {
            $cooperation_usage = db('cooperation_usage')->join('stock', 'stock.id=cooperation_usage.stock_id', 'left')->field('cooperation_usage.id,cooperation_usage.company,cooperation_usage.stock_name,cooperation_usage.stock_id,cooperation_usage.latest_cost,sum(cooperation_usage.number) as number,cooperation_usage.created_time,cooperation_usage.remake,stock.type')->where('stock.type', $data['type'])->group('cooperation_usage.latest_cost,cooperation_usage.stock_id');

            if (isset($data['ok']) && $data['ok'] != '') {
                $cooperation_usage->where(['cooperation_usage.status' => 3]);
            }
            $custom = $cooperation_usage->order('cooperation_usage.created_time desc')->select();
        } else {
            $custom = db('routine_usage')->join('stock', 'stock.id=routine_usage.stock_id', 'left')->field('routine_usage.id,routine_usage.company,routine_usage.stock_name,routine_usage.stock_id,routine_usage.latest_cost,sum(routine_usage.number) as number,routine_usage.created_time,routine_usage.remake,stock.type')->where('routine_usage.store_id', $this->us['store_id'])->where('stock.type', $data['type'])->group('routine_usage.latest_cost,routine_usage.stock_id')->where('routine_usage.status', 3)->select();

        }

        r_date($custom, 200);
    }

    /**
     * 获取库存列表
     */
    public function Stock_list_search()
    {
        $data            = Request::instance()->post(['title']);
        $custom_material = [];
        $purchase_usage  = [];
        $routine_usage   = [];
        $custom_material = db('custom_material')->field('id,company,stock_name,latest_cost,number,created_time,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where(['stock_name' => ['like', "%{$data['title']}%"]])->where('number', 'neq', 0)->select();
        foreach ($custom_material as $k => $l) {
            $custom_material[$k]['type'] = 0;
        }

        $purchase_usage = db('purchase_usage')->field('id,company,stock_name,latest_cost,number,created_time,status,content,remake')->where('type', 1)->where('number', 'neq', 0)->where('status', 3)->where(['stock_name' => ['like', "%{$data['title']}%"]])->where('store_id', $this->us['store_id'])->select();
        foreach ($purchase_usage as $k => $l) {
            $purchase_usage[$k]['type'] = 99;
        }

        $routine_usage = db('routine_usage')->join('stock', 'stock.id=routine_usage.stock_id', 'left')->field('routine_usage.id,routine_usage.company,routine_usage.stock_name,routine_usage.stock_id,routine_usage.latest_cost,sum(routine_usage.number) as number,routine_usage.created_time,routine_usage.remake,stock.type')->where('routine_usage.store_id', $this->us['store_id'])->where(['routine_usage.stock_name' => ['like', "%{$data['title']}%"]])->group('routine_usage.latest_cost,routine_usage.stock_id')->where('routine_usage.status', 3)->select();

        $cooperation_usage = db('cooperation_usage')->join('stock', 'stock.id=cooperation_usage.stock_id', 'left')->field('cooperation_usage.id,cooperation_usage.company,cooperation_usage.stock_name,cooperation_usage.stock_id,cooperation_usage.latest_cost,sum(cooperation_usage.number) as number,cooperation_usage.created_time,cooperation_usage.remake,stock.type')->group('cooperation_usage.latest_cost,cooperation_usage.stock_id')->where(['cooperation_usage.stock_name' => ['like', "%{$data['title']}%"]])->where('cooperation_usage.status', 3)->order('cooperation_usage.created_time desc')->select();


        r_date(array_merge(array_merge(array_merge($custom_material, $purchase_usage), $routine_usage), $cooperation_usage), 200);
    }

    /**
     * 获取库存列表
     */
    public function CollectingStock_list()
    {
        $data = Request::instance()->post(['type', 'ok']);
        if ($data['type'] == 0) {
            $custom = db('custom_material')->field('id,company,stock_name,status,latest_cost,number,created_time,number')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where('number', 'neq', 0)->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 0;
            }
        } else if ($data['type'] == 99) {
            $cust = db('purchase_usage')->field('id,company,stock_name,status,latest_cost,number,created_time,content,remake')->where('type', 1)->where('number', 'neq', 0);
            if (isset($data['ok']) && $data['ok'] != '') {
                $cust->where(['status' => 3]);
            }
            $custom = $cust->where('store_id', $this->us['store_id'])->order('created_time desc')->select();
            foreach ($custom as $k => $l) {
                $custom[$k]['type'] = 99;
            }
        } else if ($data['type'] == 98) {
            $custom = db('stock')->field('id,company,stock_name,latest_cost,type,class_table')->where('type', 98)->whereNull('deleted_at')->select();
            foreach ($custom as $k => $value) {
                $custom[$k]['latest_cost'] = !empty($value['latest_cost']) ? $value['latest_cost'] : 0;
                $custom[$k]['number']      = db('cooperation_usage')->where('stock_id', $value['id'])->where('status', 3)->sum('number');
                $custom[$k]['state']       = db('cooperation_usage')->where('stock_id', $value['id'])->where('status', 3)->value('status');
            }
        } else {
            $custom = db('stock')->field('id,company,stock_name,latest_cost,type,class_table')->where('type', $data['type'])->whereNull('deleted_at')->select();

            foreach ($custom as $k => $value) {
                $custom[$k]['latest_cost'] = !empty($value['latest_cost']) ? $value['latest_cost'] : 0;
                $custom[$k]['number']      = db('routine_usage')->where('store_id', $this->us['store_id'])->where('stock_id', $value['id'])->where('status', 3)->sum('number');
                $custom[$k]['state']       = db('routine_usage')->where('store_id', $this->us['store_id'])->where('stock_id', $value['id'])->value('status');
            }
        }

        r_date($custom, 200);
    }

    /**
     * 获取库存列表
     */
    public function CollectingStock_list_search()
    {

        $request = Authority::param(['invname']);
        $data    = u8cInvcDetail(null, $this->us['store_id'], 1, 200, $request['invname'], 1);
        $data    = json_decode($data, true);

        if ($data['status'] == 'success') {
            $list = $data['data'];
        } else {
            $list = null;
        }

        r_date($list, 200);
    }


    /**
     * 获取已选列表
     */
    public function get_Material_list()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('material_usage')->where(['order_id' => $data['order_id'], 'types' => $data['type']])->field('Material_id,material_name,type,square_quantity,total_price,company,unit_price,created_time,id,status,content as remake')->order('status asc')->select();
        r_date($material_usage, 200);
    }

    /**
     * 采购详情列表
     */
    public function get_routine_usage()
    {
        $params          = Authority::param(['invclcode']);
        $custom_material = [];
        $purchase_usage  = [];
        $routine_usage   = [];
        $custom_material = db('custom_material')->field('company,number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time')->where(['store_id' => $this->us['store_id'], 'status' => 0])->where(['code' => $params['invclcode']])->select();

        $purchase_usage = db('purchase_usage')->field('company,number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,status,content')->where('type', 1)->where(['code' => $params['invclcode']])->where('store_id', $this->us['store_id'])->select();

        $routine_usage = db('routine_usage')->field('company,number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,status,content')->where(['code' => $params['invclcode'], 'store_id' => $this->us['store_id']])->where('types', 1)->select();

        $routine_cart = db('routine_cart')->field('measname as company,chooseNumber as number,original_number,FROM_UNIXTIME(created_time,"%Y-%m-%d %H:%i") as created_time,status,content,id')->where(['invclcode' => $params['invclcode'], 'store_id' => $this->us['store_id']])->select();

//        foreach ($routine_cart as $k => $list) {
//            $status = db('routine_usage')->where('id', $list['id'])->value('status');
//
//            if ($status == 2) {
//                $routine_cart[$k]['status'] = 2;
//            } elseif ($status == 0) {
//                $routine_cart[$k]['status'] = 0;
//            }
//        }
        $rows = array_merge($routine_cart, array_merge($routine_usage, array_merge($purchase_usage, $custom_material)));

        foreach ($rows as $k => $item) {
            if (isset($item['original_number']) && !empty($item['original_number'])) {
                $rows[$k]['original_number'] = $item['number'];
                $rows[$k]['number']          = $item['original_number'];

            } else {
                $rows[$k]['original_number'] = $item['number'];
            }


        }
        $rows = $this->arraySort($rows, 'created_time', SORT_DESC);
        r_date($rows, 200);


    }

    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys 要排序的键字段
     * @param string $sort 排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    public function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }

    /*
     * 领用详情
     */
    public function get_Collect()
    {
        $params = Authority::param(['invclcode']);

        $routine_usage = db('material_usage')
            ->field('IF(material_usage.types=1,user.username,app_user.username) as username,FROM_UNIXTIME(material_usage.created_time,"%Y-%m-%d %H:%i") as created_time,material_usage.id,material_usage.types,material_usage.square_quantity as number,material_usage.status,material_usage.company,material_usage.content')
            ->join(config('database.db2')['database'] . '.app_user', 'app_user.id=material_usage.user_id and material_usage.types=2', 'left')
            ->join('user', 'user.user_id=material_usage.user_id and material_usage.types=1', 'left')
            ->join('usage_record', 'usage_record.id=material_usage.id', 'left')
            ->join('user user1', 'material_usage.shopowner_id=user1.user_id', 'left')
            ->where(['user1.store_id' => $this->us['store_id']])
            ->where(['usage_record.unified' => $params['invclcode']])
            ->order('material_usage.id desc')
            ->select();


        r_date($routine_usage, 200);
    }

    /*
     * 店长采购详情
     */
    public function purchaseUsage()
    {
        $params = Request::instance()->get();
        db('message')->where(['order_id' => $params['id'], 'type' => 34, 'user_id' => $this->us['user_id']])->update([
            'already' => 0, 'have' => time(),
        ]);//
        //type1采购2领用
        $purchase_usage = db('purchase_usage')->where(['id' => $params['id']])->where('store_id', $this->us['store_id'])->order('id desc')->find();
        $num            = 0;
        $pr             = 0;

        if ($purchase_usage['status'] == 3) {
            $num += $purchase_usage['number'];
            $pr  += $purchase_usage['latest_cost'] * $purchase_usage['number'];
        }
        $purchase_usage['number'] = $purchase_usage['number'] + db('material_usage')->where('Material_id', $purchase_usage['id'])->where('type', 99)->whereIn('status', [0, 1])->sum('square_quantity');

        $purchase_usage['classification'] = 99;
        $data[]                           = $purchase_usage;
        $data                             = ['stock_name' => $purchase_usage['stock_name'], 'latest_cost' => $purchase_usage['latest_cost'], 'number' => $num, 'total_price' => sprintf('%.2f', $pr), 'data' => $data];
        r_date($data, 200);
    }

    /*
     * 自购采购详情
     */
    public function CollaborativeWarehouse()
    {
        $params = Request::instance()->get();

        //type1采购2领用
        $custom_material = db('custom_material')->where(['id' => $params['id']])->where('store_id', $this->us['store_id'])->order('id desc')->find();
        $num             = 0;
        $pr              = 0;
        $num             += $custom_material['number'];

        $pr                        += $custom_material['latest_cost'] * $custom_material['number'];
        $custom_material['status'] = 3;
        $custom_material['number'] = $custom_material['number'] + db('material_usage')->where('Material_id', $custom_material['id'])->where('type', 0)->whereIn('status', [0, 1])->sum('square_quantity');
        $data[]                    = $custom_material;
        $data                      = ['stock_name' => $custom_material['stock_name'], 'latest_cost' => $custom_material['latest_cost'], 'number' => sprintf('%.2f', $num), 'total_price' => sprintf('%.2f', $pr), 'data' => $data];
        r_date($data, 200);


    }

    /**
     * 师傅材料审核
     */
    public function get_Material_To_examine()
    {
        $data = Authority::param(['id', 'status', 'content']);
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点');
        }
        db()->startTrans();
        try {
            $material_usage = db('material_usage')->where(['id' => $data['id']])->find();
            $purchase_usage = db('usage_record')
                ->field('purchase_usage.code as purchase_usageId,custom_material.code as custom_materialId,routine_usage.code as routine_usageId,routine_cart.invclcode as routine_cartId')
                ->join('purchase_usage', 'purchase_usage.code=usage_record.unified and purchase_usage.store_id=' . $this->us['store_id'] . '', 'left')
                ->join('custom_material', 'custom_material.code=usage_record.unified and custom_material.store_id=' . $this->us['store_id'] . '', 'left')
                ->join('routine_usage', 'routine_usage.code=usage_record.unified and routine_usage.types=1 and routine_usage.store_id=' . $this->us['store_id'] . '', 'left')
                ->join('routine_cart', 'routine_cart.invclcode=usage_record.unified and routine_cart.store_id=' . $this->us['store_id'] . '', 'left')
                ->where('usage_record.classification', 0)
                ->where(['usage_record.id' => $data['id']])
                ->find();
            $code           = $material_usage['code'];
            if ($purchase_usage) {
                if (!empty($purchase_usage['purchase_usageId'])) {
                    $code = $purchase_usage['purchase_usageId'];
                } elseif (!empty($purchase_usage['custom_materialId'])) {
                    $code = $purchase_usage['custom_materialId'];
                } elseif (!empty($purchase_usage['routine_usageId'])) {
                    $code = $purchase_usage['routine_usageId'];
                } elseif (!empty($purchase_usage['routine_cartId'])) {
                    $code = $purchase_usage['routine_cartId'];
                }
            }


            $unit_price = 0;
            if ($data['status'] == 1 && $material_usage['status'] != 1) {
                $op  = u8queryForStoreId($code, $this->us['store_id']);
                $u8c = json_decode($op, true);

                if ($u8c['status'] == 'success') {
                    $number = json_decode($u8c['data'], true);
                    if ($number['retcount'] == 0) {
                        throw new Exception('库存不足');
                    } else {
                        $Leftover = $number['datas'][0]['nnum'] - $material_usage['square_quantity'];
                        if ($Leftover >= 0) {
                            if(!empty($material_usage['invclasscode'])){
                                $Price=u8cGetPrice($this->us['store_id'],$code,$material_usage['invclasscode']);
                                $Price = json_decode($Price, true);
                                if($Price['status'] == 'success'){
                                    $unit_price=$Price['data'];
                                }

                            }

                            if(empty($unit_price)){
                                throw new Exception('出库失败');
                            }
                            $inter    = u8insertU8c($this->us['store_id'], $material_usage['order_id'], $material_usage['square_quantity'], $code, $unit_price);
                            $U8cinter = json_decode($inter, true);
                            if ($U8cinter['status'] != 'success') {
                                throw new Exception('审核失败');
                            }
                            $status     = $data['status'];
                            $money      = $material_usage['square_quantity'] * $unit_price;
                            //材料领用
                            db('material_usage')->where(['id' => $data['id']])->update(['status' => $status, 'content' => $data['content'], 'unit_price' => $unit_price, 'total_price' =>  round($money,2), 'total_profit' => $money, 'adopt' => time()]);
                        } else {
                            throw new Exception('库存不足');
                        }
                    }
                } else {
                    throw new Exception('请求异常，请稍后再试');
                }

            } else {
                db('material_usage')->where(['id' => $data['id']])->update(['status' => $data['status'], 'content' => $data['content'], 'adopt' => time()]);
            }

            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }

    /**
     * 获取费用已选列表
     */
    public function get_reimbursement_list()
    {
        $data = Request::instance()->post();
        if (!empty($data['user_id'])) {
            $this->us['user_id'] = $data['user_id'];
        }
        //费用报销
        if ($data['type'] == 1) {
            $quer = db('reimbursement');
            if (isset($data['isMaterial'])) {
                $quer->where('classification', 4);
            } else {
                $quer->where('classification', '<>', 4);
            }
            $reimbursement = $quer->where(['order_id' => $data['order_id'], 'type' => 1])->field('reimbursement_name,id,money,voucher,created_time,id,status,remake, content as remarks,classification,payment_notes,secondary_classification')->select();
        } else {
            $exp  = new \think\db\Expression('field(status,0,3,1,2)');
            $quer = db('reimbursement');
            if (isset($data['isMaterial'])) {
                $quer->where('classification', 4);
            } else {
                $quer->where('classification', '<>', 4);
            }
            $reimbursement = $quer->where(['order_id' => $data['order_id'], 'type' => 2])->field('reimbursement_name,id,money,voucher,created_time,id,status,remake,user_id, content as remarks,classification,payment_notes,status,remake,secondary_classification')->order($exp)->select();
            foreach ($reimbursement as $k => $item) {
                $reimbursement[$k]['user_id'] = Db::connect(config('database.db2'))->table('app_user')->where('id', $item['user_id'])->field('username')->find()['username'];
            }
        }
        foreach ($reimbursement as $k => $item) {
            $reimbursement[$k]['voucher'] = empty(unserialize($item['voucher'])) ? [] : unserialize($item['voucher']);
            $reimbursement_relation       = db('reimbursement_relation')
                ->Join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')
                ->field('bank_card.*,reimbursement_relation.receipt_number')
                ->where('reimbursement_id', $item['id'])
                ->find();
            if($item['classification'] != 4){
                $type=1;
            }else{
                $type=2;
            }
            $reimbur                      = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('relation_id', $item['id'])->where('type', $type)->where('approval.city_id', config('cityId'))->value('bi_user.username');


            if ($reimbur) {
                if ($item['status'] != 2) {
                    if ($item['status'] != 1) {
                        $reimbursement[$k]['reimbursement_name'] = $item['reimbursement_name'] . "\n" . '【当前审批人:' . $reimbur . '】';
                    } else {
                        $reimbursement[$k]['reimbursement_name'] = $item['reimbursement_name'];
                    }

                } else {
                    $reimbursement[$k]['reimbursement_name'] = $item['reimbursement_name'] . "\n" . '【当前拒绝人:' . $reimbur . '】';
                }
            }
            $title                                = array_search($item['classification'], array_column($this->list_reimbursement_type(2), 'type'));
            $reimbursement[$k]['title_secondary'] = $this->list_reimbursement_type(2)[$title]['name'];
            if (!empty($item['secondary_classification'])) {
                $title_secondary                      = array_search($item['secondary_classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $reimbursement[$k]['title_secondary'] = $reimbursement[$k]['title_secondary'] . '_' . $this->list_reimbursement_type(2)[$title_secondary]['name'];;
            }
            $reimbursement[$k]['receipt_number'] = isset($reimbursement_relation) ? $reimbursement_relation['receipt_number'] : '';
            if ($reimbursement_relation['category'] == 1 && $reimbursement_relation['binding_uid'] == $this->us['user_id']) {
                $reimbursement_relation['isMy'] = 1;
            } else {
                $reimbursement_relation['isMy'] = 0;
            }
            if ($item['classification'] != 4) {
                $reimbursement[$k]['reimbursementList'] = db('reimbursement_relation')
                    ->join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')
                    ->where('reimbursement_id', $item['id'])
                    ->field('bank_card.account_name as name,bank_card.bank_card_number as collection_number ')
                    ->find();
            }
//            else{
//            $reimbursement[$k]['reimbursementList'] = db('reimbursement_relation')->join('agency', 'agency.agency_id=reimbursement_relation.bank_id', 'left')
//                ->field('agency.agency_name as name,agency.collection_number as collection_number')
//                ->where('reimbursement_id', $item['id'])
//                ->find();

//            }

        }


        r_date($reimbursement, 200);
    }

    /**
     * 师傅报销审核
     */
    public function get_Material_To_Reimbursement(Approval $approval)
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            //材料领用
            $reimbursement = db('reimbursement')->where(['id' => $data['id']])->find();
            $cleared_time=\db('order')->where('order_id',$reimbursement['order_id'])->value('cleared_time');
            if(!empty($cleared_time)){
                throw new Exception('该订单已结算');
            }
            if ($data['status'] == 1) {
                $app_user = Db::connect(config('database.db2'))->table('app_user')->where('id', $reimbursement['user_id'])->value('username');
                $title    = array_search($reimbursement['classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $title    = '师傅' . $app_user . $this->list_reimbursement_type(2)[$title]['name'] . '报销';
                $approval->Reimbursement($data['id'], $title, $this->us['username'], $reimbursement['classification']);

                $p = ['status' => 3, 'submission_time' => time()];
            } else {
                $p = ['status' => 2, 'remake' => $data['remake'], 'submission_time' => time()];
            }
            db('reimbursement')->where(['id' => $data['id']])->update($p);
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }

    }


    /*
     * 人工结算
     */
    public function artificial_list()
    {

        $data    = Request::instance()->post();
        $capital = $cap = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->field('class_b,capital_id')->select();
        if (empty($capital)) {
            r_date(null, 300, '数据不存在');
        }
        foreach ($capital as $k => $kl) {
            $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order_capital')->join('app_user', 'app_user.id=app_user_order_capital.user_id', 'left')->where('app_user_order_capital.capital_id', $kl['capital_id'])->where('app_user_order_capital.deleted_at', 'null')->field('app_user_order_capital.work_time,app_user_order_capital.personal_price,app_user.username,app_user_order_capital.user_id')->select();
            //            echo Db::connect(config('database.db2'))->table('app_user_order_capital')->getLastSql();die;
            $capital[$k]['data'] = $reality_artificial;;
        }
        r_date($capital, 200);
    }

    /*
     * 查公司
     */
    public function u8c_corp()
    {
        $request            = Authority::param(['pk_corp']);
        $reality_artificial = Db::connect(config('database.zong'))->table('u8c_corp')->where('pk_corp', $request['pk_corp'])->field('fathercorp,innercode,pk_corp as pkCorp,store_id as storeId,unitcode,unitname,unitshortname')->find();

        r_date($reality_artificial, 200);

    }


    /*
     * 采购添加
     */
    public function purchase_usage_material(Approval $approval)
    {

        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $validate = new validate\Purchase_usage();
            if (!$validate->check($data)) {
                r_date($validate->getError(), 300);
            }

            $t1    = microtime(true);
            $t2    = microtime(true);
            $l     = ($t2 - $t1) * 1000;
            $sp_no = substr(date('YmdHis') . $l, 0, 14);
            $id    = db('purchase_usage')->insertGetId(['stock_name' => $data['stock_name'], 'company' => $data['company'], 'latest_cost' => $data['latest_cost'], 'voucher' => !empty(json_decode($data['voucher'], true)) ? serialize(json_decode($data['voucher'], true)) : '', 'sp_no' => $sp_no, 'user_id' => $this->us['user_id'], 'store_id' => $this->us['store_id'], 'created_time' => time(), 'remake' => $data['remake'], 'type' => 1, 'number' => $data['number'], 'meas' => $data['meas'], 'invcl' => $data['invcl'], 'invcl_name' => $data['invcl_name'], 'status' => 0, 'order_id' => $data['order_id'], 'address' => $data['address'], 'name' => $data['name'], 'phone' => $data['phone']]);
            $title = $this->us['username'] . '材料采购';

            db()->commit();
            $approval->Purchase($id, $title, $this->us['username'], 1, $this->us['user_id']);

            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }


    }

    /*
    * 采购收货/入库
    */
    public function purchase_usage_Warehousing()
    {
        $data = Request::instance()->post();
        //入库
        $id = db('purchase_usage')->where('id', $data['id'])->update(['status' => 3, 'notes' => $data['notes'], 'notes_voucher' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '']);
        if ($id) {
            r_date($id, 200);
        } else {
            r_date(null, 300);
        }

    }

    /*
    * 常规材料/入库
    */
    public function routine_usage_Warehousing()
    {
        $data = Request::instance()->post();
        db::startTrans();
        try {
            $routine_usage = db('routine_usage')->where('id', $data['id'])->find();

            if ($routine_usage['secondment'] == 1) {
                $secondment = \db('secondment')->where('debi_id', $routine_usage['id'])->find();

                db('routine_usage')->where('created_time', $secondment['created_time'])->where('stock_id', $secondment['stock_id'])->where(['store_id' => $secondment['lender_store_id']])->update(['storage_time' => time(), 'status' => 3]);
                db('routine_usage')->where('created_time', $secondment['created_time'])->where('stock_id', $secondment['stock_id'])->where(['store_id' => $secondment['debi_store_id']])->update(['status' => 3, 'notes' => $data['notes'], 'storage_time' => time(), 'voucher' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '']);


                db('secondment')->where('created_time', $secondment['created_time'])->where('stock_id', $secondment['stock_id'])->where(['lender_store_id' => $secondment['lender_store_id']])->update(['status' => 3]);

            } else {
                //入库
                db('routine_usage')->where('id', $data['id'])->update(['status' => 3, 'notes' => $data['notes'], 'storage_time' => time(), 'voucher' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '']);
            }
            db::commit();
            r_date(null, 200);
        } catch (Exception $exception) {
            db::rollback();
            r_date(null, 300, $exception->getMessage());
        }
    }

    //    /*
    //         * 常规材料直接入库没有收货
    //         */
    //    public function routine_usage_Warehousing()
    //    {
    //        $data = Request::instance()->post();
    //        //入库
    //        $custom = db('stock')
    //            ->where('id', $data['id'])
    //            ->find();
    //
    //        if (empty($custom)) {
    //            r_date(null, 300, '数据不存在');
    //        }
    //        $id = db('routine_usage')->insertGetId([
    //            'stock_name'   => $custom['stock_name'],
    //            'stock_id'     => $custom['id'],
    //            'store_id'     => $this->us['store_id'],
    //            'company'      => $custom['company'],
    //            'latest_cost'  => $custom['latest_cost'],
    //            'user_id'      => $this->us['user_id'],
    //            'number'       => $data['number'],
    //            'status'       => 0,
    //            'created_time' => time(),
    //        ]);
    //        if ($id) {
    //            r_date($id, 200);
    //        } else {
    //            r_date(null, 400);
    //        }
    //    }
    /*
      * 常规材料直接入库没有收货
      */
    public function routine_Warehousing(Approval $approval)
    {
        $data = Request::instance()->post();

        db()->startTrans();
        try {


            $t1    = microtime(true);
            $t2    = microtime(true);
            $l     = ($t2 - $t1) * 1000;
            $sp_no = substr(date('YmdHis') . $l, 0, 14);

            $id = db('routine_usage')->insertGetId(['store_id' => $this->us['store_id'], 'stock_name' => '材料库存增加', 'user_id' => $this->us['user_id'], 'company' => '', 'status' => 0, 'voucher' => '', 'created_time' => time(), 'types' => 2, 'remake' => $data['remake'], 'sp_no' => $sp_no, 'address' => $data['address'], 'phone' => $data['phone'], 'name' => $data['name'], 'order_id' => $data['order_id']]);

            db('routine_cart')->insertGetId(['id' => $id, 'invname' => $data['invname'], 'measname' => $data['measname'], 'invclcode' => $data['invclcode'], 'chooseNumber' => $data['number'], 'created_time' => time(), 'store_id' => $this->us['store_id']]);

            $title = $this->us['username'] . '材料采购';
            db()->commit();
            $approval->Purchase($id, $title, $this->us['username'], 2, $this->us['user_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }

    public function list_reimbursement_type($type = 1, $id = 1)
    {


        if ($type == 1) {
            if ($id == 0) {
                $data = [
                    ['name' => '建渣打拆', 'type' => 1],
                    ['name' => '小材料(不报销主材)', 'type' => 2, 'data' => [
                        ['type' => 8, 'name' => '泥工辅材'],
                        ['type' => 9, 'name' => '木工及墙板材料'],
                        ['type' => 10, 'name' => '水电工材料'],
                        ['type' => 11, 'name' => '油漆工材料'],
                        ['type' => 12, 'name' => '小耗材及小工具'],
                        ['type' => 13, 'name' => '小主材'],
                    ]],
                    ['name' => '协作人工', 'type' => 3],
                    ['type' => 7, 'name' => '运费'],

                ];

            } else {
                $data = [['name' => '返工材料成本', 'type' => 4], ['name' => '返工人工成本', 'type' => 5,], ['name' => '返工其他费用', 'type' => 6,]];
            }

            r_date($data, 200);
        } else {
            $approval = new Approval();
            return $approval->listReimbursement();
        }

    }

    public function MaterialList(OrderModel $orderModel, $order_startDate, $order_endDate, $type, $page, $limit = 20)
    {

        $material_usage = db('material_usage');
        $condition      = [];
        if (!empty($order_startDate) && !empty($order_endDate)) {

            $start                     = strtotime($order_startDate . ' 00:00:00');
            $end                       = strtotime($order_endDate . ' 23:59:59');
            $condition['created_time'] = ['between', [$start, $end]];
        }

        if (!empty($type) && $type == 3) {
            $condition['status'] = 0;
            $condition['types']  = 2;
        }
        $article = $material_usage->where('shopowner_id', $this->us['user_id'])->distinct('order_id')->where('code', '<>', 0)->whereNotNull('code')->where($condition)->field('order_id')->order('created_time desc')->page($page, $limit)->select();
        $data    = [];
        foreach ($article as $k => $item) {
            $data[$k]['order_id'] = $item['order_id'];
            $data[$k]['address']  = $orderModel->addres($item['order_id']);
            $list                 = db('material_usage')->where('order_id', $item['order_id'])->where('code', '<>', 0)->whereNotNull('code')->where($condition)->field('material_name,square_quantity,unit_price,user_id,types,total_price,status,types,id')->select();
            foreach ($list as $value) {
                if ($value['types'] == 2) {
                    $value['username'] = Db::connect(config('database.db2'))->table('app_user')->where('id', $value['user_id'])->find()['username'];
                } else {
                    $value['username'] = $this->us['username'];
                }
                $data[$k]['data'][] = $value;


            }
        }

        r_date($data, 200);

    }

    public function ReimbursementList(OrderModel $orderModel, $order_startDate, $order_endDate, $type, $page, $limit = 1)
    {
        $isMaterial    = Request::instance()->get();
        $reimbursement = db('reimbursement');
        $condition     = [];
        if (!empty($order_startDate) && !empty($order_endDate)) {

            $start                     = strtotime($order_startDate . ' 00:00:00');
            $end                       = strtotime($order_endDate . ' 23:59:59');
            $condition['created_time'] = ['between', [$start, $end]];
        }
        if (!empty($type) && $type == 4) {
            $condition['status'] = 0;
            $condition['type']   = 2;
        }
        $quer = $reimbursement;
        if (isset($isMaterial['isMaterial'])) {

            $quer->where('classification', 4);
        } else {

            $quer->where('classification', '<>', 4);
        }
        $list = $quer->where('shopowner_id', $this->us['user_id'])->where($condition)->distinct('order_id')->field('order_id ')->order('created_time desc')->page($page, $limit)->select();
        $data = [];
        foreach ($list as $k => $item) {
            $data[$k]['order_id'] = $item['order_id'];
            $data[$k]['address']  = $orderModel->addres($item['order_id']);
            $reimbur              = db('reimbursement');

            if (isset($isMaterial['isMaterial'])) {
                $reimbur->where('classification', 4);
            } else {
                $reimbur->where('classification', '<>', 4);
            }
            $lists = $reimbur->where($condition)->where('order_id', $item['order_id'])->field('id,order_id,reimbursement_name,money,user_id,type,status,classification,id')->order('created_time desc')->select();
            foreach ($lists as $value) {
                if ($value['type'] == 2) {
                    $value['username'] = Db::connect(config('database.db2'))->table('app_user')->where('id', $value['user_id'])->find()['username'];
                } else {
                    $value['username'] = $this->us['username'];
                }
                if (!empty($value['cleared_time'])) {
                    $value['status'] = 4;
                }
                if($value['classification'] != 4){
                    $type=1;
                }else{
                    $type=2;
                }
                $reimbur                      = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('relation_id', $value['id'])->where('type', $type)->where('approval.city_id', config('cityId'))->value('bi_user.username');


                if ($reimbur) {
                    if ($value['status'] != 2) {
                        if ($value['status'] != 1) {
                            $value['reimbursement_name'] =$value['reimbursement_name'] . "\n" . '【当前审批人:' . $reimbur . '】';
                        }

                    } else {
                        $value['reimbursement_name'] = $value['reimbursement_name'] . "\n" .'【当前拒绝人:' . $reimbur . '】';
                    }
                }
                $title          = array_search($value['classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $value['title'] = $this->list_reimbursement_type(2)[$title]['name'];
                unset($value['classification']);
                $data[$k]['data'][] = $value;
            }
        }
        r_date(array_values($data), 200);
    }

    /*
     * 报销详情
     */
    public function ReimbursementInfo($id)
    {

        $reimbursement = db('reimbursement')->where('id', $id)->find();
        if ($reimbursement['type'] == 2) {
            $reimbursement['username'] = Db::connect(config('database.db2'))->table('app_user')->where('id', $reimbursement['user_id'])->find()['username'];
        } else {
            $reimbursement['username'] = $this->us['username'];
        }
        if ($reimbursement['classification'] == 4) {

            $reimbursement['mainMaterialIds'] = db('capital')->whereIn('capital_id', $reimbursement['capital_id'])->field('class_b,capital_id')->select();

            $relation = db('reimbursement_relation')
                ->join('agency', 'agency.agency_id=reimbursement_relation.bank_id', 'left')
                ->where(['reimbursement_id' => $reimbursement['id']])
                ->whereIn('capital_id', array_column($reimbursement['mainMaterialIds'], 'capital_id'))
                ->field('CONCAT("账户：(",agency.collection_name,")") as collection_name,CONCAT("帐号：(",if(LENGTH(agency.collection_number)<8,REPLACE(agency.collection_number,SUBSTR(agency.collection_number FROM 5 ),"****"),REPLACE(agency.collection_number,SUBSTR(agency.collection_number FROM 5 FOR 12),"****") ),")") as collection_number,CONCAT("银行：(",agency.bank_of_deposit,")") as deposit ')
                ->select();
            $name     = "";
            if (!empty($relation)) {
                foreach ($relation as $item) {
                    $name .= $item['collection_name'] . $item['deposit'] . $item['collection_number'] . ',';
                }
            } else {
                $name = '未设置收款帐号';
            }


            $reimbursement['payment_notes'] = $name;
        } else {
            $reimbursement['mainMaterialIds'] = null;
            $reimbursement['payment_notes']   = '';
        }


        if ($reimbursement['status'] != 1) {
            if($reimbursement['classification'] == 4){
                $type=2;
            }else{
                $type=1;
            }
            $reimbursementapproval = db('approval', config('database.zong'))->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where('relation_id', $id)->where('type', $type)->where('approval.city_id', config('cityId'))->value('bi_user.username');
            if ($reimbursementapproval) {
                if ($reimbursement['status'] != 2) {
                    if ($reimbursement['status'] != 1) {
                        $reimbursement['username'] = $reimbursement['username'] . '【当前审批人：' . $reimbursementapproval . '】';
                    }

                } else {
                    $reimbursement['username'] = $reimbursement['username'] . '【当前拒绝人：' . $reimbursementapproval . '】';
                }
            }

        }

        $title = array_search($reimbursement['classification'], array_column($this->list_reimbursement_type(2), 'type'));
        if (!empty($reimbursement['secondary_classification'])) {
            $title2                           = array_search($reimbursement['secondary_classification'], array_column($this->list_reimbursement_type(2), 'type'));
            $reimbursement['title_secondary'] = '_' . $this->list_reimbursement_type(2)[$title2]['name'];
        } else {
            $reimbursement['title_secondary'] = '';
        }

        $reimbursement['title_secondary'] = $this->list_reimbursement_type(2)[$title]['name'] . $reimbursement['title_secondary'];
        $reimbursement['created_time']    = !empty($reimbursement['created_time']) ? date('y-m-d H:i', $reimbursement['created_time']) : '';
        $reimbursement['adopt']           = !empty($reimbursement['adopt']) ? date('y-m-d H:i', $reimbursement['adopt']) : '';
        $reimbursement['cleared_time']    = !empty($reimbursement['cleared_time']) ? date('y-m-d H:i', $reimbursement['cleared_time']) : '';//计算时间
        $reimbursement['voucher']         = !empty($reimbursement['voucher']) ? unserialize($reimbursement['voucher']) : null;
        r_date($reimbursement, 200);

    }

    /*
     * 审核列表条数
     */
    public function ListSummary()
    {

        $data['reimbursementMoney'] = sprintf("%.2f", db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('classification', '<>', 4)->where('status', 1)->whereNull('cleared_time')->sum('money'));//订单费用报销
        $data['materialUsageCount'] = db('material_usage')->where('shopowner_id', $this->us['user_id'])->where('code', '<>', 0)->whereNotNull('code')->where('status', 0)->count();
        $data['reimbursementCount'] = db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('type', 2)->where('status', 0)->count();
        $data['MaterialCount']      = sprintf("%.2f", db('reimbursement')->where('shopowner_id', $this->us['user_id'])->where('classification', 4)->where('status', 1)->sum('money'));
        $data['routineUusageCount'] = db('secondment')->where('lender_store_id', $this->us['store_id'])->whereNotNull('code')->where('code', '<>', 0)->where('status', 0)->count();

        r_date($data, 200);
    }

    /*
     * 材料外借
     */
    public function lend()
    {
        $data = Request::instance()->post();
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点');
        }
        db()->startTrans();
        try {
            $time = time();

            $ids = db('routine_usage')->insertGetId(['store_id' => $data['user_id'], 'stock_name' => $data['invname'], 'latest_cost' => $data['nabprice'],  'number' => '-' . $data['number'], 'code' => $data['id'], 'status' => 0, 'created_time' => $time, 'company' => $data['measname'], 'secondment' => 1, 'types' => 2]);

            $id = db('routine_usage')->insertGetId(['store_id' => $this->us['store_id'], 'user_id' => $this->us['user_id'],'stock_name' => $data['invname'], 'latest_cost' => $data['nabprice'], 'number' => $data['number'], 'code' => $data['id'], 'status' => 0, 'created_time' => $time, 'company' => $data['measname'], 'secondment' => 1, 'types' => 2]);

            db('secondment')->insertGetId(['debi_store_id' => $this->us['store_id'], 'stock_name' => $data['invname'], 'latest_cost' => $data['nabprice'], 'debi' => $this->us['user_id'], 'number' => $data['number'], 'code' => $data['id'], 'company' => $data['measname'], 'created_time' => $time, 'remake' => $data['etRemark'], 'lender' => 0, 'lender_store_id' => $data['user_id'], 'lender_id' => $ids, 'debi_id' => $id, 'types' => 2]);
            db()->commit();
            r_date(null, 200);

        } catch
        (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }

    /*
     * 可用戒掉列表
     */
    public function ItemLending()
    {

        $request = Authority::param(['invclasscode']);
        $data    = u8queryForOther($request['invclasscode'], $this->us['store_id']);
        $data    = json_decode($data, true);

        if ($data['status'] == 'success') {
            $list = $data['data'];
        } else {
            $list = null;
        }
        r_date($list, 200);


    }

    public function SecondmentDetails()
    {
        $data = Request::instance()->post();
        if ($data['type'] == 0) {
            $date   = db('custom_material')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 0])->group('latest_cost')->field('id,sum(number) as number,stock_name,latest_cost')->select();
            $number = db('custom_material')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->sum('number');
        } elseif ($data['type'] == 99) {
            $date   = db('purchase_usage')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->group('latest_cost')->field('id,sum(number) as number,stock_name,latest_cost')->select();
            $number = db('purchase_usage')->where(['id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->sum('number');
        } elseif ($data['type'] == 98) {
            $date = db('cooperation_usage')->where(['id' => $data['stock_id'], 'status' => 3])->group('latest_cost')->field('id,stock_name,latest_cost')->select();;
            $number = db('cooperation_usage')->where(['id' => $data['stock_id'], 'status' => 3])->sum('number');
        } else {
            $date   = db('routine_usage')->where(['stock_id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->group('latest_cost')->field("id,stock_name,latest_cost")->select();
            $number = db('routine_usage')->where(['stock_id' => $data['stock_id'], 'store_id' => $data['store_id'], 'status' => 3])->sum('number');
        }
        if (count($date) > 1) {
            $id = implode(array_column($date, 'id'), ',');
        } else {
            $id = $date[0]['id'];
        }


        r_date(['num' => $number, 'stock_name' => $date[0]['stock_name'], 'latest_cost' => $date[0]['latest_cost'], 'id' => $id], 200);

    }

    /*
     * 借用记录
     */
    public function QuitTheList()
    {
        $date = Authority::param(['invclcode']);
        //Debit1借方2出借方
        $secondment = \db('secondment')->field('secondment.stock_name,secondment.id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,sum(secondment.number) as number,user.username,secondment.status,secondment.company,secondment.content,secondment.debi_store_id,secondment.debi_id');
        if (isset($date['invclcode']) && $date['invclcode'] != '') {
            $secondment->where('secondment.code', $date['invclcode']);
        }
        $data = $secondment->join('user', 'user.user_id=secondment.debi', 'left')->where('secondment.debi_store_id', $this->us['store_id'])->group('secondment.stock_id,secondment.created_time,secondment.debi')->select();
        foreach ($data as $k => $i) {
            $data[$k]['Debit'] = 1;
            $data[$k]['ids']   = $i['debi_id'];
        }
        $secondments = \db('secondment')->field('secondment.stock_name,secondment.debi_id,secondment.id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,sum(secondment.number) as number,user.username,secondment.content,secondment.company,secondment.status,secondment.debi_store_id');
        if (isset($date['invclcode']) && $date['invclcode'] != '') {
            $secondments->where('secondment.code', $date['invclcode']);
        }
        $secondments = $secondments->join('user', 'user.user_id=secondment.debi', 'left')->where('secondment.lender_store_id', $this->us['store_id'])->group('secondment.stock_id,secondment.created_time,secondment.debi')->select();

        foreach ($secondments as $k => $i) {
            $secondments[$k]['Debit'] = 2;
            $secondments[$k]['ids']   = $i['debi_id'];
        }
        $userArrayList = array_values(array_merge($data, $secondments));
        $arr_key       = array_column($userArrayList, 'created_time');
        array_multisort($arr_key, SORT_DESC, $userArrayList);
        r_date($userArrayList, 200);
    }

    /*
     * 戒掉审批列表
     */
    public function routineUusageApproval()
    {
        $date       = Request::instance()->post();
        $secondment = \db('secondment')->where('code', '<>', 0)->whereNotNull('code')->field('secondment.stock_name,secondment.id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,sum(secondment.number) as number,user.username,secondment.status');
        if (!empty($date['created_time']) && $date['created_time'] != '' && !empty($date['end_time']) && $date['end_time'] != '') {
            $start = strtotime($date['created_time'] . ' 00:00:00');
            $end   = strtotime($date['end_time'] . ' 23:59:59');
            $secondment->whereBetween('secondment.created_time', [$start, $end]);
        }
        $data = $secondment->join('user', 'user.user_id=secondment.debi', 'left')->where('secondment.lender_store_id', $this->us['store_id'])->group('secondment.stock_id,secondment.created_time,secondment.debi')->order('secondment.id desc')->select();


        r_date($data, 200);
    }

    /*
     * 戒掉审批详情
     */
    public function routineUusageApprovalInfo()
    {
        $date       = Request::instance()->post();
        $secondment = \db('secondment')->field('secondment.stock_name,stock_id,lender_store_id,secondment.latest_cost,FROM_UNIXTIME(secondment.created_time,"%Y-%m-%d %H:%i:%s") as created_time,secondment.number,secondment.remake,user.username,user1.username as username1,secondment.status,user2.username as username2')->join('user', 'user.user_id=secondment.lender', 'left')->join('user user1', 'user1.user_id=secondment.debi', 'left')->join('user user2', 'user2.user_id=secondment.reviewer', 'left')->where('secondment.id', $date['id'])->find();


        $secondment['number'] = \db('secondment')->where('created_time', strtotime($secondment['created_time']))->where('stock_id', $secondment['stock_id'])->where(['lender_store_id' => $secondment['lender_store_id']])->sum('number');
        r_date($secondment, 200);
    }

    /*
     * 戒掉审批审核
     */
    public function toExamine()
    {
        $request = Authority::param(['id', 'status', 'content']);
        if ($this->us['Inventory'] == 1) {
            r_date(null, 300, '库存盘点');
        }
        $secondment = \db('secondment')->where('id', $request['id'])->find();
        db()->startTrans();
        try {
            if ($request['status'] == 1) {
                $op  = u8queryForStoreId($secondment['code'], $this->us['store_id']);
                $u8c = json_decode($op, true);

                if ($u8c['status'] == 'success') {
                    $number = json_decode($u8c['data'], true);
                    if ($number['retcount'] == 0) {
                        throw new Exception('库存不足');
                    } else {
                        $Leftover = $number['datas'][0]['nnum'] - $secondment['number'];
                        if ($Leftover >= 0) {
                            $inter    = u8outAndIn($secondment['debi_store_id'], $secondment['code'], $secondment['number'], $secondment['lender_store_id']);
                            $U8cinter = json_decode($inter, true);
                            if ($U8cinter['status'] != 'success') {
                                throw new Exception('审核失败');
                            }
                        } else {
                            throw new Exception('库存不足');
                        }
                    }
                } else {
                    throw new Exception('请求异常，请稍后再试');
                }
            }
            db('secondment')->where('id', $secondment['id'])->update(['status' => $request['status'], 'adopt' => time(), 'reviewer' => $this->us['user_id'], 'content' => $request['content']]);
            db('routine_usage')->where('id', $secondment['lender_id'])->update(['status' => $request['status'], 'adopt' => time(), 'content' => $request['content']]);
            db('routine_usage')->where('id', $secondment['debi_id'])->update(['status' => $request['status'], 'adopt' => time(), 'content' => $request['content']]);
            db()->commit();
            r_date(null, 200);

        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());

        }
    }
    /***********************************************返工后的材料已经报销***********************************************************************************/

    /*
     * 获取材料领用记录
     */
    public function CollectionRecord()
    {
        $date           = Request::instance()->post();
        $material_usage = db('material_usage')->field('app_user.username as sfusername,user.username as dzusername,material_usage.square_quantity,material_usage.code as Material_id,material_usage.types,material_usage.material_name,material_usage.unit_price')->join('usage_record', 'usage_record.id=material_usage.id', 'left')->join(config('database.db2')['database'] . '.app_user', 'app_user.id=material_usage.user_id and material_usage.types=2', 'left')->join('user', 'user.user_id = material_usage.user_id and material_usage.types=1', 'left')->where('material_usage.order_id', $date['order_id'])->where('usage_record.classification', 0)->where('material_usage.status', 1)->select();
        foreach ($material_usage as $k => $item) {
            if ($item['types'] == 2) {
                $material_usage[$k]['username'] = $item['sfusername'];
            } else {
                $material_usage[$k]['username'] = $item['dzusername'];
            }
            unset($material_usage[$k]['sfusername'], $material_usage[$k]['dzusername']);
        }

        r_date($material_usage, 200);
    }

    /*
     * 返工详情保存
     */
    public function constructionPlan()
    {
        $date = Request::instance()->post();

        db()->startTrans();
        try {
            $end_id = db('rework_end')->insertGetId(['img' => !empty($date['img']) ? serialize(json_decode($date['img'], true)) : '', 'order_id' => $date['order_id'],//材料id
                'created_time' => time(), 'remark' => $date['remark'],]);
            db('order_rework')->insertGetId(['user_id' => $this->us['user_id'], 'order_id' => $date['order_id'],//材料id
                'customer' => 2, 'reason' => $date['remark'], 'rework_end' => $end_id,]);
            $master    = isset($date['master']) ? json_decode($date['master'], true) : '';
            $material  = isset($date['material']) ? json_decode($date['material'], true) : '';
            $shopoWner = isset($date['shopoWner']) ? json_decode($date['shopoWner'], true) : '';
            if (!empty($shopoWner)) {
                foreach ($shopoWner as $item) {
                    \db('rework_form')->insertGetId(['material_id' => '',//材料id
                        'capital_id' => $item['id'],//材料id
                        'user_id' => $this->us['user_id'],//店长id
                        'order_id' => $date['order_id'],//材料id
                        'created_time' => time(), 'type' => 1,//店长id  1方案原因2施工原因3材料原因
                        'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                    ]);

                }
            }
            if (!empty($master)) {
                foreach ($master as $item) {
                    foreach ($item['arrayList'] as $key) {
                        \db('rework_form')->insertGetId(['material_id' => '',//材料id
                            'capital_id' => $key,//材料id
                            'order_id' => $date['order_id'],//材料id
                            'created_time' => time(), 'user_id' => $item['id'],//店长id
                            'type' => 2,//店长id  1方案原因2施工原因3材料原因
                            'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                        ]);

                    }
                    $order = OrderModel::get(['order_id', $date['order_id']]);
                    if ($order->state > 5) {
                        $type = 1;
                    } else {
                        $type = 2;
                    }
                    $result  = send_post(UIP_SRC . "/support-v1/rework/add", ['order_id' => $date['order_id'], 'user_ids' => $item['id'], 'type' => $type, 'source' => 2, 'reason' => $date['remark']]);
                    $results = json_decode($result, true);

                    if ($results['code'] != 200) {
                        throw  new  Exception($results['msg']);
                    }
                }
            }
            if (!empty($material)) {
                foreach ($material as $item) {
                    if (!empty($item['arrayList'])) {
                        foreach ($item['arrayList'] as $key) {
                            \db('rework_form')->insertGetId(['material_id' => $item['id'],//材料id
                                'capital_id' => $key,//材料id
                                'order_id' => $date['order_id'],//材料id
                                'user_id' => '',//店长id
                                'created_time' => time(), 'type' => 3,//店长id  1方案原因2施工原因3材料原因
                                'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                            ]);
                        }
                    } else {
                        \db('rework_form')->insertGetId(['material_id' => $item['id'],//材料id
                            'capital_id' => '',//材料id
                            'order_id' => $date['order_id'],//材料id
                            'user_id' => '',//店长id
                            'created_time' => time(), 'type' => 3,//店长id  1方案原因2施工原因3材料原因
                            'end_id' => $end_id,//店长id  1方案原因2施工原因3材料原因
                        ]);
                    }

                }
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());

        }


    }

    /*
     * 返工详情回显
     */
    public function constructionPlanInfo()
    {
        $date          = Request::instance()->post();
        $end_id        = db('rework_end')->where(['order_id' => $date['order_id'], 'id' => $date['id']])->find();
        $end_id['img'] = empty($end_id['img']) ? [] : unserialize($end_id['img']);
        $rework_form   = db('rework_form')->where('rework_form.end_id', $end_id['id'])->select();
        foreach ($rework_form as $k => $item) {
            if ($item['type'] == 1) {
                $shopoWner[] = $item;
            }
            if ($item['type'] == 2) {
                $master[] = $item;
            }
            if ($item['type'] == 3) {
                $material[] = $item;
            }
        }

        if (!empty($shopoWner)) {
            $capital_id    = array_column($shopoWner, 'capital_id');
            $shopoWnerData = \db('capital')->whereIn('capital_id', $capital_id)->field('class_b,square,company')->select();
        }


        //施工原因
        $outMaster = [];
        $masters   = empty($master) ? [] : $master;
        if (!empty($masters)) {
            foreach ($masters as $key => $v) {
                if (isset($out[$v['user_id']])) {
                    unset($masters[$key]);
                } else {
                    $outMaster[$v['user_id']] = $v;
                }
            }
            $outMasterArray = array_merge($outMaster);
            foreach ($outMasterArray as $k => $item) {
                $capital_id = [];
                foreach ($master as $l) {
                    if ($item['user_id'] == $l['user_id']) {
                        $capital_id[] = $l['capital_id'];
                    }
                    $MasterData[$k]['arrayList'] = empty($capital_id) ? [] : $capital_id;
                    $MasterData[$k]['name']      = Db::connect(config('database.db2'))->table('app_user')->where('id', $item['user_id'])->value('username');;
                }

            }
        }

        //材料原因
        $out       = [];
        $materials = empty($material) ? [] : $material;

        foreach ($materials as $key => $v) {

            if (isset($out[$v['material_id']])) {
                unset($materials[$key]);
            } else {
                $out[$v['material_id']] = $v;
            }
        }
        $outArray = array_values(array_merge($out));

        foreach ($outArray as $k => $item) {
            $capital_id = [];
            foreach ($material as $l) {
                if ($item['material_id'] == $l['material_id']) {
                    $capital_id[] = $l['capital_id'];
                }

                $data[$k]['arrayList']   = empty($capital_id[0]) ? [] : $capital_id;
                $data[$k]['user_id']     = $item['user_id'];
                $data[$k]['material_id'] = $item['material_id'];
                $lists                   = U8cIncode($item['material_id'], $this->us['store_id']);
                $lists                   = json_decode($lists, true);

                if ($lists['status'] == 'success') {

                    $data[$k]['name'] = $lists['data']['invname'];
                } else {
                    $data[$k]['name'] = '';
                }


            }

        }

        r_date(['material' => empty($data) ? [] : $data, 'master' => empty($MasterData) ? [] : $MasterData, 'shopoWner' => empty($shopoWnerData) ? [] : $shopoWnerData, 'info' => $end_id], 200);

    }

    public function constructionList()
    {

        $date       = Request::instance()->post();
        $rework_end = db('rework_end')->join('order', 'order.order_id=rework_end.order_id', 'left')->where(['rework_end.order_id' => $date['order_id']])->field('rework_end.update_time,rework_end.remark,rework_end.id,order.rework_cleared_time')->order('rework_end.id desc')->select();
        foreach ($rework_end as $k => $item) {
            $rework_end[$k]['moneyCost']       = \db('rework_reimbursement')->where(['end_id' => $item['id'], 'status' => 1])->sum('money');
            $rework_end[$k]['mast']            = empty(db('order_rework')->where(['rework_end' => $item['id']])->value('master_id')) ? 0 : 1;
            $rework_end[$k]['MaterialScience'] = \db('rework_material_usage')->where(['end_id' => $item['id'], 'status' => 1])->sum('total_price');
            $rework_end[$k]['CaseClosed']      = empty($item['update_time']) ? 0 : 1;
            if (empty($item['remark']) && empty($item['rework_cleared_time'])) {
                $rework_end[$k]['state'] = 0;
            } elseif (!empty($item['remark']) && empty($item['rework_cleared_time']) && empty($item['update_time'])) {
                $rework_end[$k]['state'] = 1;
            } elseif (!empty($item['update_time']) && empty($item['rework_cleared_time'])) {
                $rework_end[$k]['state'] = 2;
            } elseif (!empty($item['rework_cleared_time'])) {
                $rework_end[$k]['state'] = 3;
            }
        }
        r_date($rework_end, 200);
    }

    /*
     * 返工后的材料费用提交
     */
    public function ReworkMaterialUsage()
    {

        $data            = Request::instance()->post();
        $data['storeId'] = $this->us['store_id'];
        $material_usage  = json_decode($data['materialJson'], true);

        db()->startTrans();
        try {
            $materialList     = U8cForList($material_usage, $data['order_id'], $this->us['store_id']);
            $materialListCode = json_decode($materialList, true);

            if ($materialListCode['status'] == 'success') {
                $p = 0;
                foreach ($material_usage as $datum) {
                    $pp = ['order_id' => $data['order_id'], 'material_name' => $datum['material_name'], 'Material_id' => 0, 'square_quantity' => $datum['square_quantity'], 'unit_price' => $datum['unit_price'], 'type' => $datum['type'], 'company' => $datum['company'], 'total_price' => round($datum['unit_price'] * $datum['square_quantity'], 2), 'user_id' => $this->us['user_id'], 'created_time' => time(), 'shopowner_id' => $this->us['user_id'], 'adopt' => time(), 'status' => 1, 'total_profit' => $datum['unit_price'] * $datum['square_quantity'], 'types' => 1, 'end_id' => $data['id'], 'code' => $datum['Material_id']];

                    $material_usage = db('rework_material_usage')->insertGetId($pp);
                    db('usage_record')->insertGetId(['id' => $material_usage, 'type' => $datum['type'], 'user_id' => $this->us['user_id'], 'number' => $datum['square_quantity'], 'created_time' => time(), 'order_id' => $data['order_id'], 'original_number' => $datum['square_quantity'], 'unified' => $datum['Material_id'], 'classification' => 1]);


                    $p += $pp['total_price'];

                }
                $orderSMS = json_decode(sendOrder($data['order_id']), true);
                if ($orderSMS['code'] != 200) {
                    throw new Exception('编辑失败');
                }
                if ((string)$p != $data['allMoney']) {

                    throw new Exception('金额错误');
                }
            } else {
                throw new Exception($materialListCode['errormsg']);
            }

            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }

    /*
    * 返工后费用报销
    */
    public function reworkReimbursement(Approval $approval)
    {

        $data = Request::instance()->post();
        db()->startTrans();
        try {
            $reimbursementList = db('reimbursement')->where(['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money']])->find();
            if ($data['type'] == 4) {
                if (empty($data['receiptNumber'])) {
                    throw new Exception('收据编号不能为空');
                }

            }
            if (!empty($reimbursementList)) {
                throw new Exception('名称和金额重复');
            }
            $my_string                   = explode(',', str_replace('"', '', trim($data['img'], '"[""]"')));
            $data['work_wechat_user_id'] = $this->us['work_wechat_user_id'];
            $data['reserve']             = $this->us['reserve'];
//            if (empty($data['work_wechat_user_id'])) {
//                throw new Exception('请联系公司');
//            }
            $data['content'] = $data['remarks'];
            $title           = $this->us['username'] . '返工费用报销';

//            if ($wechatObj_data['errcode'] != 0) {
//                cache::set($data['order_id'], $wechatObj_data);
//                throw new Exception('企业微信提交失败');
//            }
//            sendZONG($wechatObj_data['sp_no'], 'BsAYLMzwwWDR2LiDaPhDPYfev85Hbny9WuJCeQDx6');
            $t1                   = microtime(true);
            $t2                   = microtime(true);
            $l                    = ($t2 - $t1) * 1000;
            $sp_no                = substr(date('YmdHis') . $l, 0, 14);
            $op                   = ['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money'], 'voucher' => !empty($data['img']) ? serialize($my_string) : '', 'created_time' => time(), 'user_id' => $this->us['user_id'], 'status' => 0, 'sp_no' => $sp_no, 'content' => $data['content'], 'classification' => $data['type'], 'submission_time' => time(), 'shopowner_id' => $this->us['user_id'], 'payment_notes' => $data['payment_notes'], 'end_id' => $data['id']];
            $rework_reimbursement = db('rework_reimbursement')->insertGetId($op);
            db('rework_reimbursement_relation')->insertGetId(['reimbursement_id' => $rework_reimbursement, 'capital_id' => '', 'bank_id' => $data['bankCardId'], 'money' => $data['money'], 'receipt_number' => isset($data['receiptNumber']) ? $data['receiptNumber'] : '']);
            $orderSMS = json_decode(sendOrder($data['order_id']), true);
            if ($orderSMS['code'] != 200) {
                throw new Exception('编辑失败');
            }
            db()->commit();
            $approval->Reimbursement($rework_reimbursement, $title, $this->us['username'], 18);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());

        }


    }

    /*
     * 返工费用报销列表
     */

    public function getReworkReimbursementList()
    {
        $data = Request::instance()->post();
        //费用报销
        $exp  = new \think\db\Expression('field(status,0,3,1,2)');
        $quer = db('rework_reimbursement');

        $reimbursement = $quer->where(['end_id' => $data['id']])->field('reimbursement_name,money,voucher,created_time,id,status,remake, content as remarks,classification,payment_notes')->order($exp)->select();

        foreach ($reimbursement as $k => $item) {
            $reimbursement[$k]['voucher'] = empty(unserialize($item['voucher'])) ? [] : unserialize($item['voucher']);
        }

        r_date($reimbursement, 200);
    }

    /*
     * 返工材料报销列表
     */

    public function getReworkMaterialUsageList()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('rework_material_usage')->where(['end_id' => $data['id']])->field('code as Material_id,material_name,type,square_quantity,total_price,company,unit_price,created_time,id,status,remake')->order('status asc')->select();
        r_date($material_usage, 200);
    }

    /*
     * 返工费用承担比例
     */

    public function getReworkProportion()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('rework_form')->join(config('database.db2')['database'] . '.app_user', 'app_user.id=rework_form.user_id and rework_form.type=2', 'left')->join('user', 'user.user_id=rework_form.user_id and rework_form.type=1', 'left')->where(['rework_form.end_id' => $data['id']])->where(['rework_form.type' => ['neq', 3]])->field('rework_form.id,IF(rework_form.type=1,user.username,app_user.username) as username,sum(rework_form.proportion) as proportion,sum(rework_form.money) as money,rework_form.type')->group('rework_form.user_id')->select();

        $moneyCost       = \db('rework_reimbursement')->where(['end_id' => $data['id'], 'status' => 1])->sum('money');
        $MaterialScience = \db('rework_material_usage')->where(['end_id' => $data['id'], 'status' => 1])->sum('total_price');
        $end_id          = db('rework_end')->where(['id' => $data['id']])->field('cause_analysis,summary,total,end_img,proportion,material_proportion')->find();
        foreach ($material_usage as $key => $item) {
            $material_usage[$key]['money'] = sprintf('%.2f', $moneyCost + $MaterialScience);
        }
        r_date(['data' => $material_usage, 'money' => sprintf('%.2f', $moneyCost + $MaterialScience), 'cause_analysis' => $end_id['cause_analysis'], 'summary' => $end_id['summary'], 'end_img' => empty($end_id['end_img']) ? $end_id['end_img'] : unserialize($end_id['end_img']), 'proportion' => $end_id['proportion'], 'material_proportion' => $end_id['material_proportion'],], 200);
    }

    /*
     * 返工费用承担比例提交
     */
    public function SubmissionOfCommitmentRatio()
    {
        $data = Request::instance()->post();
        if (empty($data['id'])) {
            r_date([], 3000, '参数不存在');
        }
        db()->startTrans();
        try {
            db('rework_end')->where(['id' => $data['id']])->update(['material_proportion' => $data['material_proportion'], 'proportion' => $data['proportion'],]);
            if (!empty($data['shopMasterPro'])) {
                $shopMasterPro = json_decode($data['shopMasterPro'], true);
                foreach ($shopMasterPro as $item) {
                    if ($item['id']) {
                        \db('rework_form')->where('id', $item['id'])->update(['money' => $item['money'], 'proportion' => $item['proportion']]);
                    }
                }
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());

        }

    }

    /*
     * 返工费用承担比例提交
     */
    public function ClosingReport()
    {
        $data = Request::instance()->post();
        if (empty($data['id'])) {
            r_date([], 3000, '参数不存在');
        }

        $moneyCost       = \db('rework_reimbursement')->where(['end_id' => $data['id'], 'status' => 1])->sum('money');
        $MaterialScience = \db('rework_material_usage')->where(['end_id' => $data['id'], 'status' => 1])->sum('total_price');
        db('rework_end')->where(['id' => $data['id']])->update(['cause_analysis' => $data['cause_analysis'], 'summary' => $data['summary'], 'end_img' => !empty($data['img']) ? serialize(json_decode($data['img'], true)) : '', 'update_time' => time(), 'total' => sprintf('%.2f', $moneyCost + $MaterialScience),]);

        r_date(null, 200);


    }

    public function reimbursement(Reimbursement $appReimbursement)
    {
        $params = Request::instance()->post();
        $list   = $appReimbursement->List($this->us['user_id'], strtotime($params['startTime']), $params['page'], $params['limit']);
        r_date($list, 200);

    }

    public function reimbInfo(Reimbursement $appReimbursement)
    {
        $params = Request::instance()->post();
        $list   = $appReimbursement->ListInfo($this->us['user_id'], $params['startTime']);

        foreach ($list as $k => $item) {
            $title = array_search($item->classification, array_column($this->list_reimbursement_type(2), 'type'));
            if (!empty($item['secondary_classification'])) {
                $title2                  = array_search($item['secondary_classification'], array_column($this->list_reimbursement_type(2), 'type'));
                $item['title_secondary'] = '_' . $this->list_reimbursement_type(2)[$title2]['name'];
            } else {
                $item['title_secondary'] = '';
            }
            $item['title']   = $this->list_reimbursement_type(2)[$title]['name'] . '_' . $item['title_secondary'];
            $item['voucher'] = empty($item->voucher) ? [] : unserialize($item->voucher);
        }

        r_date($list, 200);


    }


}